import { onMounted, isRef, watch, onBeforeUnmount, unref, type Ref } from 'vue'

function useEventListener(
  target: Ref<EventTarget | null> | EventTarget,
  eventName: string,
  handler: (e: Event) => any
) {
  onMounted(() => {
    if (isRef(target)) {
      watch(target, (value, oldValue) => {
        oldValue?.removeEventListener(eventName, handler)
        value?.addEventListener(eventName, handler)
      })
    } else {
      target.addEventListener(eventName, handler)
    }
  })

  onBeforeUnmount(() => {
    unref(target)?.removeEventListener(eventName, handler)
  })
}

export default useEventListener
